package sdfi.lee.Encoding;

import java.io.BufferedInputStream;
import java.net.URL;

import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsICharsetDetectionObserver;
import org.mozilla.intl.chardet.nsPSMDetector;

public class AutoEncoding {
	public static boolean found=false;
	public static String encode;
	public static String  getEncoding(String siteurl)
	{
		try
		{
			
		URL url=new URL(siteurl);
		nsDetector det = new nsDetector(nsPSMDetector.ALL) ;
		det.Init(new nsICharsetDetectionObserver(){

			@Override
			public void Notify(String charset) {
				// TODO Auto-generated method stub
				found=true;
				encode=charset;
			}
			
		});
		BufferedInputStream imp = new BufferedInputStream(url.openStream());
		
		byte[] buf = new byte[1024] ;
		int len;
		boolean done = false ;
		boolean isAscii = true ;
		   
		while( (len=imp.read(buf,0,buf.length)) != -1) {
			if (isAscii)
			    isAscii = det.isAscii(buf,len);
			if (!isAscii && !done)
	 		    done = det.DoIt(buf,len, false);
		}
		det.DataEnd();

		if (isAscii) {
		   
		   found = true ;
		   return "ASCII";
		}

		if (!found) {
		   String prob[] = det.getProbableCharsets() ;
		   for(int i=0; i<prob.length; i++) {
			encode=prob[1].toString();
		   }
		   
		}
		}
		catch(Exception ee)
		{
			ee.printStackTrace();
			
		}
		return encode;
	}
}
